import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react'
import { useFullscreen } from 'ahooks'

import video from '../../../store/video'
import SvgIcon from '../../common/svg-icon'
import { getBoundingClientRect } from '../../../util'

const FullScreen = forwardRef(({ mainRef }, ref) => {
  const { videoSize } = video

  const [isFullscreen, setIsFullscreen] = useState(false)
  const [toolbarWidth, setToolbarWidth] = useState(videoSize.w)

  useImperativeHandle(ref, () => toolbarWidth)

  const [, { setFull, exitFull }] = useFullscreen(mainRef)

  function handleClick() {
    setIsFullscreen(!isFullscreen)
    isFullscreen ? exitFull() : setFull()
  }

  useEffect(() => {
    const videoWrap = document.getElementById('videoWrap')
    if (isFullscreen) {
      videoWrap.style.height = '100%'
      videoWrap.style.width = '100%'
      const { width } = getBoundingClientRect('videoWrap')
      setToolbarWidth(width)
    } else {
      // 退出全屏，变回原来尺寸
      if (videoWrap) {
        const { w, h } = videoSize
        videoWrap.style.height = `${h}px`
        videoWrap.style.width = `${w}px`
        setToolbarWidth(w)
      }
    }
  }, [isFullscreen])

  return <SvgIcon icon="#iconfull-screen" marginRight="0" handleClick={handleClick} />
})

export default FullScreen
